<template>
  <div
    class="dh-switch"
    :class="{
      [`dh-switch--${size}`]: size,
      'is-disabled': disabled,
      'is-checked': isChecked,
    }"
    @click="SwitchClick"
  >
    <input
      class="dh-switch__input"
      type="checkbox"
      role="switch"
      :disabled="disabled"
      :name="name"
     ref="input"
    />
    <div class="dh-switch__core">
        <div class="dh-switch__core-action"></div>
        <div class="dh-switch__core-inner">
          <span v-if="activeText || inactiveText" class="dh-switch__core-inner-text">
            {{ isChecked ? activeText : inactiveText }}
          </span>
          <span v-if="activeIcon || inactiveIcon" class="dh-switch__core-inner-text">
            <Icon  :icon="(activeIcon as string)"></Icon>

          </span>
        </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch , inject } from "vue";
import type { SwitchEmits, SwitchProps } from "./type";
import { FormItemContextKey } from '@/components/Form/type'
import Icon from "../Icon/Icon.vue";
defineOptions({
  name: "DhSwitch",
  inheritAttrs: false,
});
const prpos = withDefaults(defineProps<SwitchProps>(),{
  activeValue: true,
  inactiveValue: false,
})
const emits = defineEmits<SwitchEmits>();
let innerValue = ref(prpos.modelValue);
let isChecked = computed(() => innerValue.value == prpos.activeValue);
let input = ref<HTMLInputElement>()
onMounted(()=>{
  input.value!.checked = isChecked.value
})
watch(
  () => prpos.modelValue,
  (newValue) => {
    innerValue.value = newValue;
  }
);
const activeIcon = computed(()=>{
  return isChecked.value ? prpos.activeIcon : prpos.inactiveIcon
})
const Svalidate = inject(FormItemContextKey)
const onValidate = (tirgger:string) =>{
  Svalidate?.validate(tirgger)
}
const SwitchClick = () =>{
  if(prpos.disabled) return
  
  let newValue = isChecked.value ? prpos.inactiveValue : prpos.activeValue;
    innerValue.value = newValue;
    emits("update:modelValue",newValue)
    emits("change",newValue)
    onValidate('change')
}
</script>

<style scoped></style>
